package com.jinlejia.bbs.logic;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.jinlejia.bbs.http.utils.BBSConfig;
import com.jinlejia.bbs.http.utils.DataFilter;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
 * @author 王进 on 2019/4/9.
 */

public class UploadFileLogic {
    private Context context;
    public UploadFileLogic(Context context){
        this.context = context;
    }

    public void execute(File file,final LogicCallback callback){
        final MediaType MEDIA_TYPE_MP3 = MediaType.parse("audio/mp3");
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);
        if (file != null) {
            multipartBodyBuilder.addFormDataPart("uploadFile", file.getName(), RequestBody.create(MEDIA_TYPE_MP3, file));
        }
        //构建请求体
        RequestBody requestBody = multipartBodyBuilder.build();
        Request.Builder RequestBuilder = new Request.Builder();
        RequestBuilder.url(BBSConfig.uploadFile);// 添加URL地址
        RequestBuilder.post(requestBody);
        Request request = RequestBuilder.build();
        OkHttpClient mOkHttpClient = OkHttpUtils.getInstance().getOkHttpClient();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                Map<String,Object> map = (Map<String,Object>)JSON.parse(str);
                if (DataFilter.filter(context,map)){
                    Map<String,Object> data = (Map<String, Object>) map.get("data");
                    String fileName = String.valueOf(data.get("fileName"));
                    String serverName = String.valueOf(data.get("tfsFileName"));
                    callback.onResult(fileName,serverName);
                }
            }
        });
    }

    public interface LogicCallback{
        void onResult(String fileName,String severPath);
    }
}
